package carcassonne.user;

import carcassonne.utils.StringUtils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelId;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class UserManager {

    private static final UserManager Instance = new UserManager();

    public static UserManager GetInstance() {
        return Instance;
    }

    /**
     * 维护 userID 和 UserInfo 的对应关系，相当于 mysql
     */
    private final Map<String, UserInfo> AllUsers = new ConcurrentHashMap<>();

    /**
     * 维护 token 和 userID 的对应关系来保持用户的登录状态，相当于 redis
     */
    private final Map<String, String> LoginUsers = new ConcurrentHashMap<>();

    private UserManager() {

    }

    public void Login(String token, UserInfo userInfo) {
        AllUsers.put(userInfo.id, userInfo);
        LoginUsers.put(token, userInfo.id);
    }

    public void Update(String token, UserInfo userInfo) {
        AllUsers.put(userInfo.id, userInfo);
        LoginUsers.put(token, userInfo.id);
    }

    public UserInfo UpdateNickname(String id, String nickname) {
        if (!AllUsers.containsKey(id)) return null;
        UserInfo userInfo = AllUsers.get(id);
        userInfo.nickname = nickname;
        return userInfo;
    }

    public boolean IsLoginUser(String token) {
        return LoginUsers.containsKey(token);
    }

    public String GetUserID(String token) {
        if (!IsLoginUser(token)) return null;
        return LoginUsers.get(token);
    }

    public UserInfo GetUserInfoWithToken(String token) {
        if (!IsLoginUser(token)) return null;
        String userID = LoginUsers.get(token);
        return AllUsers.get(userID);
    }

    public UserInfo GetUserInfoWithUserID(String userID) {
        return AllUsers.get(userID);
    }
}
